using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;

namespace WindowsAPI.COM
{
    [ComVisible(false)]
    public abstract class ColumnProvider : IColumnProvider
    {
        const int SHCNE_ASSOCCHANGED = 0x08000000;

        public abstract int Initialize(LPCSHCOLUMNINIT psci);
        public abstract int GetColumnInfo(int dwIndex, out SHCOLUMNINFO psci);
        public abstract int GetItemData(LPCSHCOLUMNID pscid, LPCSHCOLUMNDATA pscd, out object pvarData);


        [ComRegisterFunction]
        public static void Register(Type t)
        {
            var key = Registry.ClassesRoot.CreateSubKey(@"Folder\shellex\ColumnHandlers\" + t.GUID.ToString("B"));
            Debug.Assert(key != null, "key != null");
            key.SetValue(string.Empty, t.Name);
            key.Close();

            // Tell Explorer to refresh
            Shell32.SHChangeNotify(SHCNE_ASSOCCHANGED, 0, IntPtr.Zero, IntPtr.Zero);
        }

        [ComUnregisterFunction]
        public static void UnRegister(Type t)
        {
            try
            {
                Registry.ClassesRoot.DeleteSubKeyTree(@"Folder\shellex\ColumnHandlers\" + t.GUID.ToString("B"));
            }
            catch
            {
                // Ignore all
            }

            // Tell Explorer to refresh
            Shell32.SHChangeNotify(SHCNE_ASSOCCHANGED, 0, IntPtr.Zero, IntPtr.Zero);
        }
    }
}